<template>
  <div class="container-fluid row" style="height: 100%">
    <div
      class="col-lg-4 col-md-5 col-sm-6 position-absolute top-50 start-50 translate-middle"
    >
      <h4 class="text-center" style="line-height: 60px">
        <img
          alt="LumbaShark"
          height="80"
          src="../../assets/Logo.png"
          width="80"
        />
      </h4>
      <div class="card" v-if="pulling || store.status.pulling">
        <div class="card-body text-center">
          <span
            ><b>{{ $t("common.loading") }}</b></span
          >
        </div>
      </div>
      <div class="card text-white bg-danger mb-3" v-else-if="data.error">
        <div class="card-body">
          <div class="text-center">
            <h6>{{ $t("oauth.authenticate.failed.title") }}</h6>
            <span>{{ data.error }}</span>
          </div>
          <hr />
          <div class="card-text">
            {{ $t("oauth.authenticate.failed.descriptions.0") }}
            <ol>
              <li>{{ $t("oauth.authenticate.failed.descriptions.1") }}</li>
              <li>{{ $t("oauth.authenticate.failed.descriptions.2") }}</li>
              <li>
                {{ $t("oauth.authenticate.failed.descriptions.3") }}
                <a class="text-white" href="https://fed.smartsheep.space/t/faq"
                  ><b>{{
                    $t("oauth.authenticate.failed.descriptions.4")
                  }}</b></a
                >
              </li>
              <li>
                {{ $t("oauth.authenticate.failed.descriptions.5") }}
                <a class="text-white" href="https://discord.gg/F4SgsEfQQ3"
                  ><b>{{
                    $t("oauth.authenticate.failed.descriptions.6")
                  }}</b></a
                >
              </li>
              <li>
                {{ $t("oauth.authenticate.failed.descriptions.7") }}
                <a class="text-white" href="mailto:littlesheep.code@hotmail.com"
                  ><b>littlesheep.code@hotmail.com</b></a
                >
              </li>
            </ol>
            {{ $t("oauth.authenticate.failed.descriptions.8") }}
            <router-link
              :to="{ name: 'introduce' }"
              class="text-white"
              href="https://discord.gg/F4SgsEfQQ3"
              ><b>{{
                $t("oauth.authenticate.failed.descriptions.9")
              }}</b></router-link
            >
          </div>
        </div>
      </div>
      <div class="card" v-else>
        <div class="card-body pb-0">
          <div class="text-center">
            <div>
              <img
                :src="data.client.avatar"
                class="rounded-circle"
                width="42"
                height="42"
              />
            </div>
            <span
              >{{ data.client.client_name }}
              <span class="text-secondary">{{
                data.developer.username
              }}</span></span
            >
            <br />
            <span>{{ $t("oauth.authenticate.want") }}</span>
          </div>
        </div>
        <hr />
        <div class="card-body pt-0">
          <h6 class="text-center">{{ $t("oauth.authenticate.required") }}</h6>
          <div>
            <ul class="list-group">
              <li
                class="list-group-item"
                v-for="item in data.client.scope.split(',')"
              >
                <input
                  disabled
                  checked="checked"
                  class="form-check-input me-1"
                  type="checkbox"
                />
                <span>&nbsp;{{ scope.details[item] }}</span>
              </li>
            </ul>
          </div>
          <div class="pt-3">
            <n-popconfirm @positive-click="router.push({ name: 'introduce' })">
              <template #trigger>
                <button
                  type="button"
                  class="btn btn-secondary float-start"
                  style="width: 49%"
                >
                  {{ $t("common.actions.cancel") }}
                </button>
              </template>
              {{ $t("oauth.authenticate.cancel") }}
            </n-popconfirm>

            <button
              type="button"
              class="btn btn-success float-end"
              style="width: 49%"
              @click="grantAccess()"
            >
              {{ $t("oauth.authenticate.grant") }}
            </button>
            <br />
            <br />
            <div class="text-center">
              <span class="text-secondary"
                >{{ $t("oauth.authenticate.grant-tip") }}
                <b>{{ store.account.accountProfile.username }}</b></span
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="loading" v-show="pulling || store.status.pulling">
      <loading :active="pulling || store.status.pulling" is-full-screen />
    </div>
  </div>
</template>

<script setup>
/**
 * Flow Chart
 * User send request -> Front end -> Get client information(Backend) -> Login -> Send user access token to backend -> Get code
 */

import axiosHttp from "axios";
import Loading from "vue-element-loading";
import { useCookies } from "vue3-cookies";
import { NPopconfirm, useMessage } from "naive-ui";
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import { useStore } from "../../stores/main";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { cookies } = useCookies();
const axios = axiosHttp.create({ validateStatus: () => true });
const message = useMessage();

const store = useStore();
const router = useRouter();
const route = useRoute();

const pulling = ref(false);
const scope = ref({});
const data = ref({});

function grantAccess() {
  pulling.value = true;
  axios
    .post(
      "/api/oauth",
      { client_id: route.query["client_id"] },
      { headers: { Authorization: "Bearer " + cookies.get("access_token") } }
    )
    .then((response) => {
      pulling.value = false;
      if (response.status === 200) {
        window.location.href =
          route.query["redirect_uri"] +
          "?code=" +
          encodeURIComponent(response.data["code"]) +
          "&state=" +
          encodeURIComponent(route.query["state"]);
      } else {
        message.error(t("common.messages.request-unknown-error"));
        console.error("Request response: ", response);
        pulling.value = false;
      }
    })
    .catch((error) => {
      message.error(t("common.messages.request-unknown-error"));
      console.error(error.message);
      pulling.value = false;
    });
}

function getInformation() {
  pulling.value = true;
  const authenticateInformation = axios.get("/api/oauth", {
    params: route.query,
  });
  const scopeInformation = axios.get("/api/management/developer/scopes");

  axiosHttp.all([authenticateInformation, scopeInformation]).then(
    axiosHttp.spread((...responses) => {
      if (responses[0].status === 200 || responses[0].status === 400) {
        data.value = responses[0].data;
        scope.value = responses[1].data["data"];
        pulling.value = false;
      } else {
        message.error(t("common.messages.request-unknown-error"));
        console.error("Request response errors: ", responses);
        pulling.value = false;
      }
    })
  );
}

getInformation();
</script>
